package demo4.mapper;

import demo4.pojo.UserInfo;
import demo4.util.DBUtil;
import demo4.util.IDBUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

@Component
public class UserMapper implements IUserMapper{
    @Autowired
    private IDBUtil dbUtil;
    @Override
    public int insert(UserInfo userInfo) {
        try (Connection connection=dbUtil.getConnection();){
            String sql="INSERT INTO userinfo(username,password,nickname,age) " +
                    "VALUES(?,?,?,?)";
            PreparedStatement ps=connection.prepareStatement(sql);
            ps.setString(1, userInfo.getUsername());
            ps.setString(2, userInfo.getPassword());
            ps.setString(3, userInfo.getNickname());
            ps.setInt(4,userInfo.getAge());
            return ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return 0;
    }

    @Override
    public UserInfo selectByusername(String username) {
        try (Connection connection= dbUtil.getConnection();){
            String sql="SELECT id,username,password,nickname,age "+
                       "FROM userinfo " +
                       "WHERE username=? ";
            PreparedStatement ps=connection.prepareStatement(sql);
            ps.setString(1,username);
            ResultSet rs=ps.executeQuery();
            if(rs.next()){
                UserInfo userInfo=new UserInfo();
                userInfo.setId(rs.getInt("id"));
                userInfo.setUsername(rs.getString("username"));
                userInfo.setPassword(rs.getString("password"));
                userInfo.setNickname(rs.getString("nickname"));
                userInfo.setAge(rs.getInt("age"));
                return userInfo;
            }else {
                System.out.println("登录失败");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public List<UserInfo> selectAll() {
        List<UserInfo> userList=new ArrayList<>();
        try (Connection connection= dbUtil.getConnection();){
            String sql="SELECT id,username,password,nickname,age "+
                       "FROM userinfo";
            Statement statement=connection.createStatement();
            ResultSet rs=statement.executeQuery(sql);
            while (rs.next()){
                UserInfo userInfo=new UserInfo();
                userInfo.setId(rs.getInt("id"));
                userInfo.setUsername(rs.getString("username"));
                userInfo.setPassword(rs.getString("password"));
                userInfo.setNickname(rs.getString("nickname"));
                userInfo.setAge(rs.getInt("age"));
                userList.add(userInfo);

            }

        } catch (SQLException e) {
            e.printStackTrace();
        }
        return userList;
    }
}
